# encoding=utf-8
# author:梁子龙
import logging

from fastapi import APIRouter, Depends, HTTPException
#
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from starlette import status

from api.user_mgt.user_schemas import CreateUserSchema, UserLoginRepSchema, UserLoginSchema
from db.user.user_dao import UserDao
from utils.dependencies import CommonQueryParams, get_db
from utils.jwt_utils import create_token
from utils.password_hash import get_hash_password, verify_password

router = APIRouter()

_dao = UserDao()
log = logging.getLogger("emp")


# oauth2 = OAuth2PasswordBearer(tokenUrl="token")


@router.get("/users", description="fenye", summary="分页查询")
def get(session: Session = Depends(get_db), commons: CommonQueryParams = Depends()):
    return _dao.get(session, offset=commons.offset, limit=commons.limit)


@router.get("/users/{pk}/", description="fenye", summary="单个查询")
def get_by_id(pk: int, session: Session = Depends(get_db)):
    return _dao.get_by_id(session, pk)


@router.post("/users/", description="用户", summary="用户注册")
def create_user(obj_in: CreateUserSchema, session: Session = Depends(get_db)):
    obj_in.password = get_hash_password(obj_in.password)
    return _dao.create(session, obj_in)


@router.post("/login/", description="用户", summary="登录", response_model=UserLoginRepSchema)
def login(obj_in: UserLoginSchema, session: Session = Depends(get_db)):
    #
    user = _dao.get_user_by_username(session, obj_in.username)
    log.info(user)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"{obj_in.username}不存在")
    if not verify_password(obj_in.password, user.password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="密码错误")
    return {
        "id": user.id,
        "username": user.username,
        "real_name": user.real_name,
        "token": create_token(user.username),

    }


@router.post("/auth/", description="接口文档认证表单")
def auth(form_data: OAuth2PasswordRequestForm = Depends(), session: Session = Depends(get_db)):
    """

    :param form_data:
    :param session:
    :return:
    """
    user = _dao.get_user_by_username(session, form_data.username)
    log.info(user)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"{obj_in.username}不存在")
    if not verify_password(form_data.password, user.password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="密码错误")
    return {
        "access_token": create_token(str(user.id) + ":" + user.username),
        "token_type": "bearer",

    }
